package login;

import login.User.User;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCHelper {//连接数据库
    private static ResultSet rs=null;
    private  static PreparedStatement stmt;
    private  static Connection conn;
    private static String url="jdbc:mysql://localhost:3306/yuntaojie";

    private  static String username="root";
    private  static String password="123";

    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //执行修改
    public  static int update(String sql,Object... params){
        try {
            getConnection();
            stmt=conn.prepareStatement(sql);
            int i=1;
            for (Object param:params) {
                stmt.setObject(i,param);
                i++;
            }

            return  stmt.executeUpdate();
        } catch (SQLException e) {
            System.out.println("执行更新出错"+e.getMessage());
        }
        return -1;
    }

    public static ResultSet query(String sql,Object ... params) {//查询

        try{
            getConnection();
            stmt = conn.prepareStatement(sql);
            int i = 1;
            for (Object param : params) {
                stmt.setObject(i, param);
                i++;
            }
            rs = stmt.executeQuery();
        }catch(SQLException e){
            System.out.println("执行查询出错"+e.getMessage());
        }
        return rs;
    }


    public static ResultSet queryUser(String sql) {
        getConnection();
        try{
            stmt = conn.prepareStatement(sql);
            rs =  stmt.executeQuery();

        }catch(SQLException e){
            System.out.println("执行查询出错"+e.getMessage());
        }
        return rs;
    }


    //新键
    public static void create(User u,String sql) throws SQLException {
        getConnection();
        PreparedStatement stmt;
        stmt = conn.prepareStatement(sql);
        stmt.setString(1,u.getName());
        stmt.setString(2,u.getPassword());
        stmt.setString(3,u.getRealName());
        stmt.setString(4,  u.getBirthDate());
        stmt.setString(5,u.getEmail());
        stmt.setString(6,u.getTelephone());
        stmt.setString(7,u.getAddress());
        stmt.setInt(8,u.getPostcode());
        stmt.execute();
    }


    private static Connection getConnection() {
        try{
            if(conn==null){
                conn= DriverManager.getConnection(url,username,password);
            }
        }catch(SQLException e){
            System.out.println("连接服务器错误"+e.getMessage());
        }
        return conn;
    }
    public static void close(){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            rs=null;
        }
    }
}